package com.farm.common.component;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.util.List;
import java.util.Random;

@Component
@Slf4j
public class ExcelComponent {
    private final StringRedisTemplate redisTemplate;

    public ExcelComponent(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public <T,E> String writeExcelList(String fileName,String tableName,  Class<T> t, List<E> ex) {

        log.info("导出准备开始===");
        if (ObjectUtil.isEmpty(fileName)){
            fileName = "ningExport";
        }

        ExportInfoPayload payload = new ExportInfoPayload();
        Thread thread = Thread.currentThread();
        // long tId = thread.getId();
        int tId = 10000 + new Random().nextInt(900000);
        // 通知当前线程id，供切断任务使用
        payload.setProgress("start");
        payload.setMessage(tId + "");

        ByteArrayOutputStream out = null;
        InputStream fileInputStream = null;
        try {
            payload.setProgress("read");
            payload.setMessage(null);
            payload.setCount(ex.size());
            payload.setProgress("save");
            payload.setMessage(null);
            payload.setCount(null);
            // 文件临时路径
            String tmpDir =  "farmExport/" + tId;
            String tmpFileName = fileName+".xlsx";
            String filePath = tmpDir + "/" + tmpFileName;
            File file = new File(filePath);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            // File tmpFile = new File(filePath);

            out = new ByteArrayOutputStream();
            // ExcelWriter writer = EasyExcel.write(out, t).build();
            ExcelWriter writer = new ExcelWriterBuilder()
                    .autoCloseStream(true)
                    .file(file)
                    .head(t)
                    .build();
            // xlsx文件上上限是104W行左右,这里如果超过104W需要分Sheet
            WriteSheet writeSheet = new WriteSheet();
            writeSheet.setSheetName(fileName);
            writer.write(ex, writeSheet);
            writer.finish();
            fileInputStream = new ByteArrayInputStream(out.toByteArray());

            MultipartFile uploadFile = new MockMultipartFile(fileName,fileName,".xlsx",fileInputStream);
            //excel上传到obs
            String url = "";

            payload.setProgress("end");
            // payload.setUrl(rtf.getData().toString());

            int lastIndexOfSlash =  URLDecoder.decode(url).lastIndexOf("/");
            // 如果找到了斜杠
            if (lastIndexOfSlash != -1) {
                // 使用substring获取最后一个斜杠之后的子字符串
                String substring = URLDecoder.decode(url).substring(URLDecoder.decode(url).lastIndexOf("/") + 1);
                payload.setUrl(String.format("%s/%s", "", substring));
            }

            return filePath;
        } catch (Exception e) {
            payload.setProgress("error");
            payload.setMessage(e.getMessage());
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
